const svc = require('../util/service')
const logger = require('log4js').getLogger()
const config = require('../util/config')

module.exports = (req, res) => {
    svc.handlePost(req, res, (reqObj, resolve) => {
        if (!reqObj.phone) {
            resolve({
                result: -1,
                msg: '缺少phone'
            })
            return
        }
        const mongoMng = require('../mng/mongoMng')
        if (!mongoMng.db) {
            logger.error('[' + __filename + ':' + __line + ']', '未连接mongo')
            resolve({
                result: -1,
                msg: '系统错误'
            })
            return
        }
        mongoMng.db.collection('user').find({
            promoter: reqObj.phone
        }).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                resolve([])
                return
            }

            var promotees = []
            var customer_phones = []
            result.forEach(item => {
                promotees.push({
                    phone: item.phone,
                    returnPromoterMoney: 0,
                    willReturnPromoterMoney: 0,
                    confirmingReturnPromoterMoney: 0
                })
                customer_phones.push(item.phone)
            })

            var promise0 = new Promise(resolve => {
                mongoMng.db.collection('bill').aggregate([{
                    $match: {
                        customer_phone: {
                            $in: customer_phones
                        },
                        returnPromoterMoney: {
                            $ne: null
                        }
                    }
                }, {
                    $group: {
                        _id: '$customer_phone',
                        returnPromoterMoney: {
                            $sum: '$returnPromoterMoney'
                        }
                    }
                }]).toArray((err, result) => {
                    if (err) {
                        logger.error('[' + __filename + ':' + __line + ']', err)
                        resolve([])
                        return
                    }
                    resolve(result)
                })
            }),
            promise1 = new Promise(resolve => {
                mongoMng.db.collection('bill').aggregate([{
                    $match: {
                        customer_phone: {
                            $in: customer_phones
                        },
                        returnPromoterTime: null,
                        returnTime: {
                            $ne: null
                        }
                    }
                }, {
                    $group: {
                        _id: '$customer_phone',
                        returnMoney: {
                            $sum: '$returnMoney'
                        }
                    }
                }]).toArray((err, result) => {
                    if (err) {
                        logger.error('[' + __filename + ':' + __line + ']', err)
                        resolve([])
                        return
                    }
                    resolve(result)
                })
            }),
            promise2 = new Promise(resolve => {
                mongoMng.db.collection('bill').find({
                    customer_phone: {
                        $in: customer_phones
                    },
                    returnTime: null,
                    payStatus: {
                        $nin: [3, 13]
                    },
                    tkStatus: {
                        $nin: [3, 13]
                    }
                }).toArray((err, result) => {
                    if (err) {
                        logger.error('[' + __filename + ':' + __line + ']', err)
                        resolve([])
                        return
                    }
                    resolve(result)
                })
            })
            Promise.all([promise0, promise1, promise2]).then(result => {    
                promotees.forEach(item => {
                    for (var i = 0; i < result[0].length; ++i) {
                        if (result[0][i]._id == item.phone) {
                            item.returnPromoterMoney = result[0][i].returnPromoterMoney
                            break
                        }
                    }
                })
    
                promotees.forEach(item => {
                    for (var i = 0; i < result[1].length; ++i) {
                        if (result[1][i]._id == item.phone) {
                            item.willReturnPromoterMoney = Math.round(result[1][i].returnMoney / config.returnRate * config.returnPromoterRate * 100) / 100
                            break
                        }
                    }
                })
    
                promotees.forEach(item => {
                    for (var i = 0; i < result[2].length; ++i) {
                        if (result[2][i].customer_phone == item.phone) {
                            let money = 0
                            if (result[2][i].taobaoTradeParentId) {
                                money = parseFloat(result[2][i].feeString) * config.returnPromoterRate
                            } else if (result[2][i].orderId) {
                                result[2][i].skuList.forEach(_item => {
                                    money += _item.actualFee * config.returnPromoterRate
                                })
                                money = Math.round(money * 100) / 100
                            } else if (result[2][i].tradeParentId) {
                                money = parseFloat(result[2][i].pubSharePreFee) * config.returnPromoterRate
                            }
                            item.confirmingReturnPromoterMoney += money
                        }
                    }
                    item.confirmingReturnPromoterMoney = Math.round(item.confirmingReturnPromoterMoney * 100) / 100
                })
    
                resolve(promotees)
            })
        })
    })
}
